import 'package:flutter/material.dart';

class TabBarKeepAlivePage extends StatefulWidget {
  const TabBarKeepAlivePage({super.key});

  @override
  _TabBarKeepAlivePageState createState() => _TabBarKeepAlivePageState();
}

class _TabBarKeepAlivePageState extends State<TabBarKeepAlivePage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("TabBar + KeepAlive 示例")),
      body: Column(
        children: [
          Container(
            color: Colors.blue,
            child: TabBar(
              controller: _tabController,
              labelColor: Colors.white,
              unselectedLabelColor: Colors.white70,
              indicatorColor: Colors.white,
              tabs: [
                Tab(text: "首页"),
                Tab(text: "消息"),
                Tab(text: "设置"),
              ],
            ),
          ),
          Expanded(
            child: TabBarView(
              controller: _tabController,
              children: [
                MyTabPage("首页"),
                MyTabPage("消息"),
                MyTabPage("设置"),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

// 继承 StatefulWidget，并使用 AutomaticKeepAliveClientMixin
class MyTabPage extends StatefulWidget {
  final String title;

  MyTabPage(this.title);

  @override
  _MyTabPageState createState() => _MyTabPageState();
}

class _MyTabPageState extends State<MyTabPage>
    with AutomaticKeepAliveClientMixin {
  int _counter = 0;

  @override
  bool get wantKeepAlive => true; // 让页面保持状态，不被销毁

  @override
  Widget build(BuildContext context) {
    super.build(context); // 这一行必须加，否则状态可能不会正确保持
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text("${widget.title} 页面"),
          Text("计数: $_counter",
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
          ElevatedButton(
            onPressed: () {
              setState(() {
                _counter++;
              });
            },
            child: Text("增加计数"),
          ),
        ],
      ),
    );
  }
}
